<?php 
class ModuleLatest extends Controller {
	function fetch() {
		$config		=& $this->locator->get('config');
		$currency	=& $this->locator->get('currency');
		$database	=& $this->locator->get('database');
		$language	=& $this->locator->get('language');
		$image		=& $this->locator->get('image');
		$tax		=& $this->locator->get('tax');
		$template	=& $this->locator->get('template');
		$url		=& $this->locator->get('url');
		$catalog	=& $this->locator->get('catalog');
	
		if (!$config->get('latest_status')) { return; }

		$language->load('extension/module/latest.php');
				
		$limit = $config->has('latest_limit')?$config->get('latest_limit'):$config->get('config_max_rows');

		$view = $this->locator->create('template');

		$view->set('tpl', $template);
		
		$view->set('id', 'latest');
		
		$view->set('heading_title', $language->get('heading_title'));

		$sql = "select * from product p left join product_description pd on (p.product_id = pd.product_id) left join image i on (p.image_id = i.image_id) where p.status = '1' and pd.language_id = '?' and p.date_available <= now() order by p.date_added desc, VIEWED limit ?";
		$products = $database->getRows($database->parse($sql, $language->getId(), $limit));
		
		if (!$products) { return; } //don't show box if there are no products
		
		$product_data = array();
		
		foreach ($products as $product) {
			$price_old = '';
			$price = $product['price'];
			$spcprice = $catalog->getSpecialPrice($product['product_id'], $product['price']);
			if ($spcprice){
				$price_old = $price;
				$price = $spcprice;
			}
			
			$query = array(
        		'product_id' => $product['product_id']
      		);
						
			$product_data[] = array(
				'product_id'	=> $product['product_id'],
				'name'  		=> $product['name'],
				'description'	=> ($config->get('latest_max_desc'))?trim(substr(strip_tags($product['description']), 0, $config->get('latest_max_desc'))) . '...':NULL,
				'href'  		=> $url->href('product', FALSE, array('product_id' => $product['product_id'])),
				'thumb' 		=> $image->resize($product['filename'], $config->get('latest_image_width'), $config->get('latest_image_height')),
				'price' 		=> $currency->format($tax->calculate($price, $product['tax_class_id'], $config->get('config_tax'))),
				'price_old' 	=> (@$price_old)?$currency->format($tax->calculate($price_old, $product['tax_class_id'], $config->get('config_tax'))):NULL,
				'action'	 	=> $url->href('cart', FALSE, $query),
			);
		}

		// columnizer code
		if ($config->get('latest_columnizer')) {
			$coldata = $template->columnizer($config->get('latest_cpr'), count($product_data));
			$view->set('style', 'width:'.$coldata['colwidth'].'%');
		}
			
		$view->set('products', $product_data);
		
		$view->set('atc', $config->get('latest_atc'));
		
		return $view->fetch('common/grid.tpl');
	}
}
?>
